package com.devunion.salon.client.app.mvc.view;

import com.devunion.salon.client.Constants;
import com.devunion.salon.client.rpc.DepartmentService;
import com.devunion.salon.client.rpc.ProductService;
import com.devunion.salon.client.app.bean.ProductModel;
import com.devunion.salon.client.app.bean.DepartmentModel;
import com.devunion.salon.client.app.bean.ProductHistoryModel;
import com.devunion.salon.client.app.bean.search.ProductSearchPagingLoadConfig;
import com.devunion.salon.client.app.bean.search.ProductHistoryPaggingLoadConfig;
import com.devunion.salon.client.app.mvc.SalonEvents;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Events;
import com.extjs.gxt.ui.client.Style;
import com.extjs.gxt.ui.client.event.*;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Record;
import com.extjs.gxt.ui.client.data.*;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.*;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonBar;
import com.extjs.gxt.ui.client.widget.form.*;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.Event;

import java.util.List;
import java.util.ArrayList;

/**
 * @author spetrakovsky
 */
public class ProductView extends View {

    private ProductModel product;

    public ProductView(Controller controller) {
        super(controller);
    }

    protected void handleEvent(AppEvent<?> event) {
        if (event.type == SalonEvents.NAVIGATE_PRODUCT_VIEW) {

            this.product = new ProductModel();
            product.setProperties(((ProductModel) event.data).getProperties());
            initComponent();
        }
    }

    public void initComponent() {
        VerticalPanel vp = new VerticalPanel();
        ContentPanel content = Registry.get(Constants.APP_CENTER_PANEL);
        content.removeAll();


        TabPanel tabPanel = new TabPanel();
        //tabPanel.setWidth(800);

        TabItem generalTab = new TabItem("General Info");
        fillGneralInfo(generalTab);
        tabPanel.add(generalTab);

        TabItem imageTab = new TabItem("Product Image");
        filleProductImage(imageTab);
        tabPanel.add(imageTab);

        final TabItem historyTab = new TabItem("History");
        fillHistory(historyTab);
        tabPanel.add(historyTab);

        vp.add(tabPanel);
        content.add(vp);

        content.layout();
    }

    private void fillGneralInfo(TabItem generalTab) {
        //generalTab.setLayout(new FitLayout());

        FormData formData = new FormData();
        FieldSet gi = new FieldSet();
        gi.setLayout(new FormLayout());
        gi.setTitle("General Info");
        gi.setHeading("General Info");

        TextField<String> nameField = new TextField<String>();
        nameField.setFieldLabel("Name");
        nameField.setName("name");
        gi.add(nameField, formData);


        TextField<String> barCodeField = new TextField<String>();
        barCodeField.setFieldLabel("Bar Code");
        barCodeField.setName("barCode");
        gi.add(barCodeField, formData);

        TextField<String> descriptionField = new TextField<String>();
        descriptionField.setFieldLabel("Description");
        descriptionField.setName("description");
        gi.add(descriptionField, formData);

        //
        /*
        RpcProxy<ListLoadConfig, ListLoadResult<VendorModel>> vendorRpcProxy = new RpcProxy<ListLoadConfig, ListLoadResult<VendorModel>>() {
            protected void load(ListLoadConfig groupingLoadConfig, AsyncCallback<ListLoadResult<VendorModel>> listAsyncCallback) {
                VendorService.App.getInstance().findVendors(groupingLoadConfig, listAsyncCallback);
            }
        };
        BaseListLoader<ListLoadConfig, ListLoadResult<VendorModel>> vendorLoader =
                new BaseListLoader<ListLoadConfig, ListLoadResult<VendorModel>>(vendorRpcProxy);
        vendorLoader.load();
        ListStore<VendorModel> vendorStore = new ListStore<VendorModel>(vendorLoader);

        ComboBox<VendorModel> vendorBox = new ComboBox<VendorModel>();
        vendorBox.setFieldLabel("Vendor");
        vendorBox.setEmptyText("Select vendor...");
        vendorBox.setDisplayField("name");
        vendorBox.setWidth(150);
        vendorBox.setStore(vendorStore);
        vendorBox.setTypeAhead(true);
        vendorBox.setTriggerAction(ComboBox.TriggerAction.ALL);
        gi.add(vendorBox, formData);

         */
        //
        RpcProxy<ListLoadConfig, ListLoadResult<DepartmentModel>> rpcProxy = new RpcProxy<ListLoadConfig, ListLoadResult<DepartmentModel>>() {
            protected void load(ListLoadConfig groupingLoadConfig, AsyncCallback<ListLoadResult<DepartmentModel>> listAsyncCallback) {
                DepartmentService.App.getInstance().getDepartments(groupingLoadConfig, listAsyncCallback);
            }
        };
        BaseListLoader<ListLoadConfig, ListLoadResult<DepartmentModel>> loader =
                new BaseListLoader<ListLoadConfig, ListLoadResult<DepartmentModel>>(rpcProxy);
        loader.load();
        ListStore<DepartmentModel> departmentStore = new ListStore<DepartmentModel>(loader);

        ComboBox<DepartmentModel> departmentBox = new ComboBox<DepartmentModel>();
        departmentBox.setFieldLabel("Department");
        departmentBox.setEmptyText("Select department...");
        departmentBox.setStore(departmentStore);
        departmentBox.setName("inventoryDepartment");
        departmentBox.setDisplayField("name");

        departmentBox.setEditable(false);
        departmentBox.setTriggerAction(ComboBox.TriggerAction.ALL);
        gi.add(departmentBox, formData);

        CheckBox taxableBox = new CheckBox();
        taxableBox.setFieldLabel("Taxable Item");
        gi.add(taxableBox, formData);

        CheckBox priceOverrideBox = new CheckBox();
        priceOverrideBox.setFieldLabel("Price Override");
        gi.add(priceOverrideBox, formData);

        CheckBox discountBox = new CheckBox();
        discountBox.setFieldLabel("Discount");
        discountBox.setName("discount");
        gi.add(discountBox, formData);


        FieldSet si = new FieldSet();
        si.setLayout(new FormLayout());
        si.setTitle("Store");
        si.setHeading("Store");


        NumberField priceField = new NumberField();
        priceField.setFieldLabel("Price");
        priceField.setName("price");
        si.add(priceField, formData);

        NumberField markup = new NumberField();
        markup.setFieldLabel("Murkup");
        markup.setName("markup");
        si.add(markup, formData);

        NumberField retailPriceField = new NumberField();
        retailPriceField.setFieldLabel("Retail Price");
        retailPriceField.setName("retailPrice");
        si.add(retailPriceField, formData);

        TextField<String> uomField = new TextField<String>();
        uomField.setFieldLabel("UOM");
        uomField.setName("uom");
        gi.add(uomField, formData);

        NumberField reorderAtField = new NumberField();
        reorderAtField.setFieldLabel("Reorder At");
        reorderAtField.setName("reorderAt");
        si.add(reorderAtField, formData);

        NumberField qtyField = new NumberField();
        qtyField.setFieldLabel("QTY");
        qtyField.setName("qty");
        si.add(qtyField, formData);

        si.setCollapsible(true);

        FormPanel formPanel = new FormPanel();
        formPanel.setHeaderVisible(false);
        formPanel.setAutoHeight(true);
        formPanel.add(gi);
        formPanel.add(si);

        ButtonBar buttonBar = new ButtonBar();
        buttonBar.add(new Button("Save", new SelectionListener<ButtonEvent>(){
            public void componentSelected(ButtonEvent ce) {
                ProductService.App.getInstance().saveProduct(product, new AsyncCallback<ProductModel>() {
                    public void onFailure(Throwable throwable) {
                        throwable.printStackTrace();
                    }

                    public void onSuccess(ProductModel productModel) {
                        fireEvent(new AppEvent(SalonEvents.NAVIGATE_PRODUCT_LIST_VIEW));
                    }
                });
            }
        }));
        buttonBar.add(new Button("Save as New", new SelectionListener<ButtonEvent>(){
            public void componentSelected(ButtonEvent ce) {
                // todo
                fireEvent(new AppEvent(SalonEvents.NAVIGATE_PRODUCT_LIST_VIEW));
            }
        }));
        buttonBar.add(new Button("Cancel", new SelectionListener<ButtonEvent>(){
            public void componentSelected(ButtonEvent ce) {
                fireEvent(new AppEvent(SalonEvents.NAVIGATE_PRODUCT_LIST_VIEW));
            }
        }));
        formPanel.add(buttonBar);

        FormBinding formBinding = new FormBinding(formPanel, true);
        formBinding.bind(product);
        generalTab.add(formPanel);
    }

    private void fillHistory(final TabItem hiptoryTab) {
        RpcProxy proxy = new RpcProxy<ProductHistoryPaggingLoadConfig, PagingLoadResult<ProductHistoryModel>>() {
            protected void load(ProductHistoryPaggingLoadConfig loadConfig, AsyncCallback<PagingLoadResult<ProductHistoryModel>> pagingLoadResultAsyncCallback) {
                ProductService.App.getInstance().findProductHistory(loadConfig, pagingLoadResultAsyncCallback);
            }
        };

        // dataLoader
        BasePagingLoader dataLoader = new BasePagingLoader<ProductHistoryPaggingLoadConfig, PagingLoadResult<ProductModel>>(proxy);
        ProductHistoryPaggingLoadConfig loadConfig = new ProductHistoryPaggingLoadConfig();
        loadConfig.setSortInfo(new SortInfo("time", Style.SortDir.DESC));
        loadConfig.setProductId(product.getId());
        dataLoader.useLoadConfig(loadConfig);
        dataLoader.setRemoteSort(true);
        dataLoader.load(0, 15);

        final ListStore<ProductHistoryModel> store = new ListStore<ProductHistoryModel>(dataLoader);
        List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
        columns.add(new ColumnConfig("name", "Name", 100));
        columns.add(new ColumnConfig("barCode", "Bar Code", 100));
        columns.add(new ColumnConfig("retailPrice", "Retail Price", 100));
        columns.add(new ColumnConfig("markup", "Markup", 100));
        columns.add(new ColumnConfig("qty", "QTY", 100));
        columns.add(new ColumnConfig("uom", "UOM", 100));
        columns.add(new ColumnConfig("reorderAt", "Reorder At", 100));
        columns.add(new ColumnConfig("taxable", "Taxable", 100));
        columns.add(new ColumnConfig("discount", "Discount", 100));
        columns.add(new ColumnConfig("priceOverride", "Price Override", 100));
        columns.add(new ColumnConfig("vendor.code", "Vendor", 100));
        columns.add(new ColumnConfig("inventoryDepartment.name", "Type", 100));
        columns.add(new ColumnConfig("time", "Date", 100));


        ColumnModel cm = new ColumnModel(columns);

        Grid<ProductHistoryModel> productGrid = new Grid<ProductHistoryModel>(store, cm);
        productGrid.setLoadMask(true);
        productGrid.setBorders(true);
        productGrid.setAutoExpandColumn("name");
        productGrid.setAutoHeight(true);
        productGrid.setAutoWidth(true);

        VerticalPanel panel = new VerticalPanel();
        hiptoryTab.add(panel);

        panel.add(productGrid);

        PagingToolBar toolBar = new PagingToolBar(15);
        toolBar.bind(dataLoader);

        panel.add(toolBar);
        panel.layout();
    }

    private void filleProductImage(TabItem imageTab) {
        // todo
        imageTab.add(new Label("TBD! fake image."));
        imageTab.add(new Image("tempimg/sample_product_photo.gif"));

    }
    
}
